package mbms.mobilebudget;

import java.sql.SQLException;

import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.User;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;

public class MainActivity  extends OrmLiteBaseActivity<DatabaseHandler>{

	//private DatabaseHandler db;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}
	
	public void redirectRegisterUser (View view ){
		Intent intent = new Intent (this, RegistrationActivity.class);
		startActivity(intent);
	}
	public void loginUser(View view) throws SQLException {
		EditText userName= ((EditText) findViewById(R.id.editText1));
		EditText pass= ((EditText) findViewById(R.id.editText2));

	    String username = userName.getText().toString();
	    String password = pass.getText().toString();
	    User loggingUser = new User();
	    loggingUser.setUsername(username);
	    loggingUser.setPassword(password);
		
	    
	    User user = null; //= login.loginUser(loggingUser, db);
	  	Dao<User, Integer> userDao = getHelper().getUserDao();
	  	QueryBuilder<User, Integer> queryBuilder = userDao.queryBuilder();
	  	Where<User, Integer> where = queryBuilder.where();
	  	where.eq(User.USERNAME_FIELD_NAME, username);
	  	where.and();
	  	where.eq(User.PASSWORD_FIELD_NAME,password);
	  	PreparedQuery<User> preparedQuery = queryBuilder.prepare();
	  	user = userDao.queryForFirst(preparedQuery);
	  	
		if(user == null|| user.getId()==null){
			userName.setText("");
			pass.setText("");
			Toast.makeText(getApplicationContext(), 
					"Wrong username/password combination", Toast.LENGTH_SHORT).show();	
		}
		else{
			Toast.makeText(getApplicationContext(), 
					"Login successful!", Toast.LENGTH_LONG).show();	
			Intent intent = new Intent (this, OperationsActivity.class);
			intent.putExtra("loggedInUser", user);
			startActivity(intent);
		}
		
	    

	    
	 //   
	   // 
	}


}
